package com.webinsky.common.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailUtils {
	
	public static class EmailFrom {
		public String fromEMail;
		public String formName;
	}
	
	public static class EmailSent {
		public String []recievers;
		public String body;
		public String subject;
	}
	
	public static class EmailSmtpServre {
		// smtp setting
		public String smtpServer;
		public String smtpUserName;
		public String smtpPassword;
		public int smtpPort;
		public boolean smtpIsSSL;
	}
	
	public static class EmailContent {
		public EmailFrom from;
		public EmailSent sender;
		public EmailSmtpServre smtpServer;
	}
	
	/**
	 * @param subject
	 * @param body
	 * @param recievers
	 * @throws MessagingException 
	 * @throws UnsupportedEncodingException 
	 */
	public static void sendMail(EmailContent content) throws UnsupportedEncodingException, MessagingException{
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");   
		// 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", content.smtpServer.smtpServer);
        props.setProperty("mail.smtp.port", String.valueOf(content.smtpServer.smtpPort));
        // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");
        if ( content.smtpServer.smtpIsSSL ){
        	props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", String.valueOf(content.smtpServer.smtpPort));
        }
		Session session= Session.getInstance(props);
		Transport transport = session.getTransport();
		MimeMessage message = new MimeMessage(session);
		// 设置发件人
		message.setFrom(new InternetAddress(content.from.fromEMail, content.from.formName, "UTF-8"));
		// 设置收件人
		Address[] addresses = new Address[content.sender.recievers.length];
		for ( int i = 0; i < content.sender.recievers.length; i ++ ){
			addresses[i] = new InternetAddress(content.sender.recievers[i]);
		}
		message.setRecipients(MimeMessage.RecipientType.TO, addresses);
		// 邮件主题
        message.setSubject(content.sender.subject, "UTF-8");
        // 邮件正文
        message.setContent(content.sender.body, "text/html;charset=UTF-8");
        // 设置显示的发件时间
        message.setSentDate(new Date());
        // 设置服务器
        transport.connect(content.smtpServer.smtpUserName, content.smtpServer.smtpPassword);
        // 发送
        transport.sendMessage(message, addresses);
	}
}
